﻿
using Microsoft.Owin.Hosting;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{

    class Program
    {
        #region 激活关闭窗口事件

        // 定义控制台事件类型
        enum ConsoleEvent
        {
            CTRL_C = 0,
            CTRL_BREAK = 1,
            CTRL_CLOSE = 2,
            CTRL_LOGOFF = 5,
            CTRL_SHUTDOWN = 6
        }

        #region 激活关闭窗口事件
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerAppClose, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerAppClose);

        /// <summary>
        /// 关闭窗口时的事件
        /// </summary>
        /// <param name="CtrlType"></param>
        /// <returns></returns>
        static bool HandlerAppClose(int CtrlType)
        {
            Console.WriteLine("关闭窗口事件被激活");
            Console.WriteLine("do something...");
            KillBarTender();
            return false;
        }

        #endregion

        #endregion
        public static void Main(string[] args)
        {//注册窗口关闭事件
            bool bRet = SetConsoleCtrlHandler(cancelHandler, true);
            try
            {

                // 获取本机主机名
                string hostName = Dns.GetHostName();

                // 解析主机名获取IP地址列表
                IPAddress[] ipAddresses = Dns.GetHostEntry(hostName).AddressList;

                // 筛选IPv4地址（排除IPv6）
                string ipv4Address = ipAddresses
                    .FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?
                    .ToString();

                if (ipv4Address != null)
                {
                    Console.WriteLine("本机IPv4地址: " + ipv4Address);
                }
                else
                {
                    Console.WriteLine("未找到IPv4地址");
                }

                //端口号
                string port = "9000";
                //电脑所有ip地址都启用该端口服务


                //string baseAddress = "http://192.168.2.242:" + port + "/";
                string baseAddress = "http://" + ipv4Address + ":" + port + "/";
                //启动OWIN host 
                using (WebApp.Start<Startup>(url: baseAddress))
                {
                    // Create HttpClient and make a request to api/values 
                    HttpClient client = new HttpClient();

                    var response = client.GetAsync(baseAddress + "api/print/test").Result;

                    Console.WriteLine(response);
                    Console.WriteLine("time:"+DateTime.Now);
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                    Console.ReadLine();
                }
                //打印服务所用端口号
                Console.WriteLine("Http服务端口：" + port);
                //测试结果
                //创建HttpCient测试webapi 

            }
            catch (Exception ex)
            {
                Console.WriteLine("Http服务初始化失败！");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
         
          


        }

        static void KillBarTender()
        {
            try
            {
                foreach (var process in Process.GetProcessesByName("bartend"))
                {
                    process.Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error killing BarTender: {ex.Message}");
            }
        }


        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="myOwinServer"></param>
        public void closeOwin(IDisposable myOwinServer)
        {
            myOwinServer.Dispose();
        }
    }
}
